<template>
  <section class="waitingNotice-list">
    <a-page-header
      style="background-color: #fff"
      title="待发通知单"
      @back="() => $router.go(-1)"
    />
    <!-- 统计模块 -->
    <section class="staticis">
      <a-row
        type="flex"
        justify="space-around"
        align="middle"
        style="height: 100px"
      >
        <a-col span="8">
          <a-statistic title="待发送数量" :value="noticeCount" />
        </a-col>
        <a-col
          span="8"
          style="
            border-left: 1px solid #f5f5f5;
            border-right: 1px solid #f5f5f5;
          "
        >
          <a-statistic
            title="应收总额"
            :precision="2"
            :value="receivableAmount"
          />
        </a-col>
        <a-col span="8">
          <a-statistic title="需收总额" :precision="2" :value="actualAmount" />
        </a-col>
      </a-row>
    </section>

    <!-- 表格 -->
    <a-table
      :dataSource="dataList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      rowKey="id"
      :scroll="{ x: 'max-content' }"
      class="mt-10"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <template
        #customFilterDropdown="{
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          column,
        }"
      >
        <div style="padding: 8px">
          <a-input
            ref="searchInput"
            placeholder="请输入租客名称"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block"
            @change="
              (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
            "
            @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
            type="primary"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button
            size="small"
            style="width: 90px"
            @click="handleReset(clearFilters, confirm)"
          >
            重置
          </a-button>
        </div>
      </template>

      <template #customFilterIcon="{ filtered, column }">
        <template v-if="column.key == 'owner_name'">
          <search-outlined
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </template>
        <template v-else>
          <filter-filled />
        </template>
      </template>

      <template #title>
        <a-row
          type="flex"
          justify="space-between"
          class="table-header"
          align="middle"
          style="
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 20px;
            padding-left: 10px;
            padding-right: 10px;
          "
        >
          <a-col :span="12">
            <a-range-picker
              v-model:value="dateRange"
              class="range-picker"
              @change="onRangeChange"
              :ranges="{
                本周: [
                  moment().startOf('week').subtract('weeks'),
                  moment().endOf('week').subtract('weeks'),
                ],
                本月: [
                  moment().startOf('months').subtract('months'),
                  moment().endOf('months').subtract('months'),
                ],
              }"
            />
          </a-col>
          <a-col :span="6" style="display: flex; justify-content: flex-end">
            <a-button
              type="primary"
              ghost
              @click="
                () => {
                  settingVisible = true;
                }
              "
            >
              <template #icon><SettingOutlined /></template>
              发送设置
            </a-button>
            <a-button
              type="primary"
              @click="addPaymentNotice"
              style="margin-left: 10px"
              :disabled="selectedRowKeys.length == 0"
              >生成缴费通知单</a-button
            >
          </a-col>
        </a-row>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'costType'">
          <span>{{ record.cost_type_txt || "-" }}</span>
        </template>
        <template v-if="column.key === 'actualPayment'">
          <span>{{ text || "0.00" }}</span>
        </template>
        <template v-if="column.key === 'timeout_status'">
          <span v-if="text == 0">正常</span>
          <span v-else style="color: #ff3141">逾期</span>
        </template>
        <template v-if="column.key === 'settle_status'">
          <span v-if="text == 2" style="color: #87d068">{{
            record.settle_status_txt
          }}</span>
          <span v-else style="color: #108ee9">{{
            record.settle_status_txt
          }}</span>
        </template>
        <template v-if="column.key === 'owner_name'">
          <a @click.stop="toOwnerDetail(record)">
            {{ text }}
          </a>
        </template>
      </template>
    </a-table>

    <notice-setting
      @closeTag="settingClose"
      @success="settingSuccess"
      :visible="settingVisible"
    >
    </notice-setting>

    <add-notice
      @closeDrawer="addNoticeClose"
      @success="addNoticeSuccess"
      :visible="addNoticeVisible"
      :ids="selectedRowKeys"
    >
    </add-notice>

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="ownerId"
      @cancel="ownerDetailVisible = false"
    />
  </section>
</template>

<script>
import { defineComponent, ref, computed, watch, reactive, toRefs } from "vue";
import request from "../../../common/utils/request";
import { useRouter } from "vue-router";
import {
  SearchOutlined,
  SettingOutlined,
  FilterFilled,
} from "@ant-design/icons-vue";
import moment from "moment";
import NoticeSetting from "./NoticeSetting.vue";
import AddNotice from "../AllBills/AddNotice.vue";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";

export default defineComponent({
  name: "waitingNoticeList",
  components: {
    SearchOutlined,
    SettingOutlined,
    NoticeSetting,
    AddNotice,
    OwnerDetailDrawer,
    FilterFilled,
  },
  setup() {
    const $router = useRouter();

    const noticeCount = ref();
    const receivableAmount = ref();
    const actualAmount = ref();
    const dateRange = ref([]);

    const costTypeList = ref([]);
    const selectedCostTypeList = ref([]);
    const timeoutStatusList = ref([]);
    const settleStatusList = ref([]);
    const selectedTimeoutStatusList = ref([]);
    const selectedSettleStatusList = ref([]);

    const searchText = ref("");
    const searchedColumn = ref("");
    const searchInput = ref();
    const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      searchText.value = selectedKeys[0];
      searchedColumn.value = dataIndex;
      getTableData();
    };

    const handleReset = (clearFilters, confirm) => {
      clearFilters();
      searchText.value = "";
      confirm();
    };

    const dataList = ref([]);
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const getTableData = () => {
      loading.value = true;
      let params = {
        page: page.value,
        limit: limit.value,
        start_time:
          dateRange.value.length > 0
            ? moment(dateRange.value[0]).format("YYYY-MM-DD")
            : "",
        end_time:
          dateRange.value.length > 0
            ? moment(dateRange.value[1]).format("YYYY-MM-DD")
            : "",
      };

      if (searchText.value) {
        params.keywords = searchText.value;
      }
      if (
        selectedSettleStatusList.value &&
        selectedSettleStatusList.value.length > 0
      ) {
        params.settle_status = selectedSettleStatusList.value;
      }
      if (
        selectedTimeoutStatusList.value &&
        selectedTimeoutStatusList.value.length > 0
      ) {
        params.timeout_status = selectedTimeoutStatusList.value;
      }
      request
        .post("/org", "/notice/staticList", { ...params })
        .then((res) => {
          dataList.value = res.list;
          total.value = res.total ? res.total : 0;
          noticeCount.value = res.noticeCount && res.noticeCount;
          receivableAmount.value = res.receivableAmount && res.receivableAmount;
          actualAmount.value = res.actualAmount && res.receivableAmount;
        })
        .finally(() => {
          loading.value = false;
        });
    };

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      selectedTimeoutStatusList.value = filters.timeout_status;
      selectedSettleStatusList.value = filters.settle_status;
      selectedCostTypeList.value = filters.cost_type;
    };

    const getFilterList = () => {
      request
        .get("/org", "/notice/listInit", {})
        .then((res) => {
          costTypeList.value = res.returnData.cost_type;
          timeoutStatusList.value = res.returnData.timeout_status;
          settleStatusList.value = res.returnData.settle_status;
        })
        .finally(() => {
          getTableData();
        });
    };

    const columns = computed(() => {
      return [
        {
          title: "租客名称",
          dataIndex: "owner_name",
          key: "owner_name",
          ellipsis: true,
          onFilter: (value, record) =>
            record.owner_name
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                console.log(searchInput.value);
                searchInput.value.focus();
              }, 100);
            }
          },
          customFilterDropdown: true,
        },
        {
          title: "费用类型",
          dataIndex: "cost_type",
          key: "costType",
          // filters:
          //   costTypeList.value && costTypeList.value.length
          //     ? costTypeList.value.map((item) => ({
          //         value: item.key.toString(),
          //         text: item.name,
          //       }))
          //     : [],
          // filterMultiple: true,
          // defaultFilteredValue: selectedCostTypeList.value,
        },
        {
          title: "楼宇名称",
          dataIndex: "build_name",
          key: "buildName",
        },
        {
          title: "楼号/房号",
          dataIndex: "room_info",
        },
        {
          title: "账单金额",
          dataIndex: "bill_amount",
          key: "billAmount",
        },
        {
          title: "应收金额",
          dataIndex: "receivable_payment",
          key: "receivablePayment",
        },
        {
          title: "实收金额",
          dataIndex: "actual_payment",
          key: "actualPayment",
        },
        {
          title: "需收金额",
          dataIndex: "actual_retreat",
          key: "actualRetreat",
        },
        {
          title: "应收日期",
          dataIndex: "receivable_payment_date",
          key: "receivablePaymentDate",
        },
        {
          title: "逾期状态",
          dataIndex: "timeout_status",
          key: "timeout_status",
          filters:
            timeoutStatusList.value && timeoutStatusList.value.length
              ? timeoutStatusList.value.map((item) => ({
                  value: item.key.toString(),
                  text: item.name,
                }))
              : [],
          filterMultiple: true,
          defaultFilteredValue: selectedTimeoutStatusList.value,
        },
        {
          title: "结清状态",
          dataIndex: "settle_status",
          key: "settle_status",
          filters:
            settleStatusList.value && settleStatusList.value.length
              ? settleStatusList.value.map((item) => ({
                  value: item.key.toString(),
                  text: item.name,
                }))
              : [],
          filterMultiple: true,
          defaultFilteredValue: selectedSettleStatusList.value,
        },
      ];
    });

    const init = () => {
      page.value = 1;
      getFilterList();
    };

    init();

    const state = reactive({
      selectedRowKeys: [],
      selectedRowAmount: 0,
      ownerId: 0,
      ownerDetailVisible: false,
    });

    const onSelectChange = (selectedRowKeys, selectedRows) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys, selectedRows);
      state.selectedRowKeys = selectedRowKeys;
      if (selectedRows.length > 0) {
        let i = 0;
        selectedRows.map((item) => {
          i += Number(item.bill_amount);
        });
        state.selectedRowAmount = i;
      }
    };

    const noticeSetting = () => {};

    const onRangeChange = (dates, dateString) => {
      page.value = 1;
    };

    const settingVisible = ref(false);

    const settingClose = () => {
      settingVisible.value = false;
    };

    const settingSuccess = (data) => {
      settingClose();
      console.log("addBillCloseaddBillCloseaddBillClose", data);
    };

    watch(
      [
        page,
        limit,
        dateRange,
        selectedCostTypeList,
        selectedTimeoutStatusList,
        selectedSettleStatusList,
      ],
      () => {
        getTableData();
      }
    );

    const addNoticeVisible = ref(false);
    const addPaymentNotice = () => {
      console.log(state.selectedRowKeys);
      let params = state.selectedRowKeys;
      request
        .post("/org", "/notice/beforeVerify", {
          billIds: params,
        })
        .then((res) => {
          addNoticeVisible.value = true;
        });
    };

    const addNoticeClose = () => {
      addNoticeVisible.value = false;
    };

    const addNoticeSuccess = () => {
      addNoticeVisible.value = false;
    };

    const toOwnerDetail = (record) => {
      state.ownerId = record.owner_id;
      state.ownerDetailVisible = true;
    };

    return {
      ...toRefs(state),
      dataList,
      pagination,
      loading,
      onSelectChange,
      handleTableChange,
      columns,
      costTypeList,
      selectedCostTypeList,
      timeoutStatusList,
      selectedTimeoutStatusList,
      settleStatusList,
      selectedSettleStatusList,
      noticeCount,
      receivableAmount,
      actualAmount,
      dateRange,

      handleSearch,
      handleReset,
      searchInput,

      noticeSetting,
      addPaymentNotice,
      addNoticeVisible,
      addNoticeClose,
      addNoticeSuccess,
      onRangeChange,
      moment,
      settingVisible,
      settingClose,
      settingSuccess,
      toOwnerDetail,
    };
  },
});
</script>

<style lang="less" scoped>
.waitingNotice-list {
  padding: 10px;

  .staticis {
    background: #fff;
    margin-top: 10px;
    width: 100%;
    padding: 10px;

    :deep(.ant-col) {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    :deep(.ant-statistic-title) {
      text-align: center;
    }

    :deep(.ant-statistic-content) {
      text-align: center;
    }
  }
}
</style>
